#define DBG_ENABLE
#define DBG_LEVEL  DBG_INFO
#define DBG_SECTION_NAME  "host_serial"
#include "HostSerialApp.h"
#include <rtdbg.h>

#define SAMPLE_UART_NAME       "uart2"

/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
static struct rt_semaphore tx_sem;
static rt_device_t serial;
/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}
static rt_err_t uart_output(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&tx_sem);

    return RT_EOK;
}
static void serial_thread_entry(void *parameter)
{
    uint8_t readBuff[256];
    int readLen = 0;
    uint8_t index;
    while (1)
    {
        rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        readLen = rt_device_read(serial,-1,readBuff,256);
        if(readLen>0)
        {
            for(i=0; i<readLen; i ++)
            {
                
            }
        }
    }
}

int init_host_serial(void)
{
        /* 查找系统中的串口设备 */
    serial = rt_device_find(SAMPLE_UART_NAME);
    if (!serial)
    {
        LOG_E("find %s failed!\n", SAMPLE_UART_NAME);
        return RT_ERROR;
    }
    else 
    {
        LOG_I("find %s success!\n", SAMPLE_UART_NAME);
    }
         /* 初始化信号量 */
     struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; /* 配置参数 */
     rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config);
     /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    rt_sem_init(&tx_sem, "tx_sem", 0, RT_IPC_FLAG_FIFO);
     rt_device_open(serial, RT_DEVICE_FLAG_DMA_RX | RT_DEVICE_FLAG_DMA_TX);
     rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config);
     rt_device_set_rx_indicate(serial, uart_input);
     rt_device_set_tx_complete(serial, uart_output);
     rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 20, 10);
     if (thread)
     {
        rt_thread_startup(thread);
     }
     else
     {
        LOG_E("create serial thread failed!\n");
        return RT_ERROR;
     }
     return RT_EOK;
}
INIT_APP_EXPORT(init_host_serial);